<?php
namespace App\Http\Controllers;
use App\Models\Comment;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Schema;

class CommentController extends WxBaseController{
    protected $except=['index','zan','unzan'];
    //获取评论
    public function index($model,$id,$num=10){
        $comments = Comment::where(['target_id'=>$id,'model'=>$model])->simplePaginate($num);
        return $this->apiReturn(true,'success',$comments);
    }
    //发表评论
    public function store(){
        $input = request();
        $con=keywords_check($input->con);
        $params =[
            'model'=>$input->model,
            'target_id'=>$input->target_id,
            'content'=>$con,
            'recommended'=>$input->recommended,
            'pic'=>$input->pic,
            'avatar'=>$this->auth()->avatarUrl,
            'nickname'=>$this->auth()->nickname,
            'wxuser_id'=>$this->auth()->id,
            'zan'=>0
        ];
        $comment = Comment::create($params);
        if(Schema::hasColumn($input->model,'recommended')){
            $avg = Comment::where(['model'=>$input->model,'target_id'=>$input->target_id])->avg('recommended');
            DB::table($input->model)->where('id',$input->target_id)->update(['recommended'=>ceil($avg)]);
        }else{
            return $this->apiReturn(false,'不存在推荐指数字段');
        }
        return $this->apiReturn(true,'success',$comment);
    }
    //点赞
    public function zan(){
        $model=request()->model;
        $target_id=request()->target_id;
        $id=request()->id;

        //更新点赞
        $zan = Comment::where(['model'=>$model,'target_id'=>$target_id,'id'=>$id]);
        $zan->increment('zan');
        return $this->apiReturn(true,'success',$zan->get(['zan']));
    }
}